package com.qike.duola.socket;

/**
 * @program: baoxiu
 * @author: Eric
 * @create: 2020-05-31 15:15
 */

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.qike.duola.service.DuolaTransOrderService;
import com.qike.duola.vo.TransListVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.stereotype.Controller;
import org.springframework.stereotype.Service;
import org.springframework.web.bind.annotation.RestController;

import javax.websocket.*;
import javax.websocket.server.PathParam;
import javax.websocket.server.ServerEndpoint;
import java.io.IOException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.CopyOnWriteArraySet;

/**
 * 运输单长连接
 */
@Component
@ServerEndpoint("/newTransOrder/{param}")
//@ServerEndpoint("/newTransOrder")
public class NewTransOrderSocket {

    public static DuolaTransOrderService  transOrderService;
//    @Autowired
//    private DuolaTransOrderService transOrderService;

    /*客户端会话Session*/
    private Session session;
    private Integer planId;
    private String carNo;
    /*线程安全Set 用于存放每个客户端处理消息的对象，用Set为不重复*/
    private static ConcurrentHashMap< NewTransOrderSocket,Object> webSocketSet = new ConcurrentHashMap<>();
    private static ConcurrentHashMap<Object, NewTransOrderSocket> webKeySet = new ConcurrentHashMap<>();

    /**
     * webSocket 链接建立之后进行调用
     *
     * @param session
     */
    @OnOpen
    public void onOpen(Session session, @PathParam("param") String param) {
        this.session = session;
//        if (planId==0){
//            planId= null;
//        }
        String[] split = param.split("&");
        this.planId = Integer.valueOf(split[0]);
        if (split.length>1){
            this.carNo = split[1];
        }
        //将新建立的连接添加到Set集合里
        webSocketSet.put(this,planId+","+carNo);
        webKeySet.put(planId+","+carNo,this);
        System.out.println("webSocket 有新的连接建立/现在的连接数量:" + webSocketSet.size());
    }
//    @OnOpen
//    public void onOpen(Session session) {
//        this.session = session;
//        this.planId = planId;
//        //将新建立的连接添加到Set集合里
//        webSocketSet.put(this,null);
//        System.out.println("webSocket 有新的连接建立/现在的连接数量:" + webSocketSet.size());
//    }

    /**
     * 连接关闭调用
     */
    @OnClose
    public void onClose() {
        //将旧连接从Set集合清除
        webSocketSet.remove(this);
        System.out.println("webSocket 有连接关闭/现在的连接数量:" + webSocketSet.size());
    }

    /**
     * 收到客户端信息后调用方法
     *
     * @param message
     * @throws IOException
     */
    @OnMessage
    public void onMessage(String message) throws IOException {
        // 群发消息,遍历所有会话对象,轮询发送消息
//        for (NewPlanOrderSocket socket:webSocketSet){
//            socket.session.getBasicRemote().sendText("收到客户端发来信息【群发消息】:"+message);
//        }
    }

    /**
     * 发生错误时调用
     *
     * @param throwable
     */
    @OnError
    public void onError(Throwable throwable) {
        throwable.printStackTrace();
    }

    /**
     * 收到客户端发送消息
     *
     * @param message
     * @throws IOException
     */
//    @Async
    public void sendMessage(String message) throws IOException {
        ConcurrentHashMap<Object,List<TransListVo>> map = new ConcurrentHashMap<>();
        for (Map.Entry<Object, NewTransOrderSocket> integerNewTransOrderSocketEntry : webKeySet.entrySet()) {
            Object key = integerNewTransOrderSocketEntry.getKey();
            String[] split = key.toString().split(",");
            String planId = split[0];
            String carNo = split[1];
            List<TransListVo> listVos = transOrderService.TransList(Integer.valueOf(planId), carNo);
            map.put(key,listVos);
        }
        for (Map.Entry<NewTransOrderSocket, Object> entry : webSocketSet.entrySet()) {
//            if (planId.equals(entry.getValue())) {
            if (map.get(entry.getValue())!=null) {
                entry.getKey().session.getBasicRemote().sendText(JSONObject.toJSONString(map.get(entry.getValue())));
            }
//                entry.getKey().session.getBasicRemote().sendText(JSON.toJSONString(listVos));
        }
    }
}


